﻿using System;
using System.Net;
using System.Collections;
using System.ComponentModel;
using System.Timers;
using System.Windows.Data;

namespace Wimat.Collections
{
    public class LazyCurrentCollectionView : ListCollectionView
    {
        #region .ctor
        public LazyCurrentCollectionView(IList list)
            : base(list)
        {

        }
        #endregion

        #region Interval

        private double _LazyCurrentChangedDelay = 100;
        public double LazyCurrentChangedDelay
        {
            get { return _LazyCurrentChangedDelay; }
            set
            {
                _LazyCurrentChangedDelay = value;
                if (_timer != null)
                {
                    _timer.Interval = _LazyCurrentChangedDelay;
                }
            }
        }
        #endregion

        #region LazyCurrent
        public event EventHandler LazyCurrentChanged;
        public object LazyCurrent
        {
            get
            {
                return CurrentItem;
            }
        }

        private Timer _timer;
        private DateTime _currentChangedStamp;
        protected override void OnCurrentChanged()
        {
            base.OnCurrentChanged();
            _currentChangedStamp = DateTime.Now;
            if (_timer == null)
            {
                _timer = new Timer();
                _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
                _timer.AutoReset = false;
                _timer.Interval = LazyCurrentChangedDelay;
                _timer.Start();
            }
            else if (_timer.Enabled)
            {
                _timer.Stop();
                _timer.Start();
            }
            else
            {
                _timer.Start();
            }
        }
        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var d3 = _currentChangedStamp;
            var d2 = DateTime.Now;
            var d1 = e.SignalTime;
            var dt = d2 - d1;
            var dt2 = d3 - d1;
            Dispatcher.BeginInvoke(new OnLazyCurrentChangedDelegate(OnLazyCurrentChanged));
        }
        private delegate void OnLazyCurrentChangedDelegate();
        private void OnLazyCurrentChanged()
        {
            if (LazyCurrentChanged != null)
            {
                LazyCurrentChanged(this, EventArgs.Empty);
            }
            OnPropertyChanged(new PropertyChangedEventArgs("LazyCurrent"));
        }
        #endregion
    }
}
